package supertrunfo;

import daos.LoginDAOS;
import domain.Usuario;
import java.sql.SQLException;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;
import validacao.validacao;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class AlteraConta extends javax.swing.JInternalFrame {

    Usuario login = new Usuario();
    private static ResourceBundle myResources;
    private static final Logger log = Logger.getLogger(AlteraConta.class.getName());

    /** Creates new form AlteraConta */
    public AlteraConta(String titulo, boolean resizable, boolean closeable, boolean maximizable, boolean iconifiable) {
        super(titulo, resizable, closeable, maximizable, iconifiable);
        
        try {

            Handler console = new ConsoleHandler();
            Handler file = new FileHandler("C:\\SuperTropa.log");

            /*Define que na consola apenas aparece log com nível superior ou
              a warning e no ficheiro deve aparecer o log de qualquer nível
             */

            console.setLevel(Level.INFO);
            file.setLevel(Level.ALL);
            //Define o formato de output do ficheiro como XML
            file.setFormatter(new SimpleFormatter());
            //Adiciona os handlers para ficheiro e console
            log.addHandler(file);
            log.addHandler(console);
            //Ignora os Handlers definidos no Logger Global
            log.setUseParentHandlers(false);
        }
        catch(IOException io){
            log.warning("O ficheiro hellologgin.xml não pode ser criado");
        }

        if (Login.LinguaAtual.equals("Português")) {
           myResources =  ResourceBundle.getBundle("Message_pt_BR",Locale.getDefault());
        }
        else {
           myResources =  ResourceBundle.getBundle("Message_en_US",Locale.ENGLISH);
        }

        log.info("Tela de alterar cadastro iniciada.");
        initComponents();
        
        getRootPane().setDefaultButton(bAlterar);
        bAlterar.setToolTipText(myResources.getString("alteraC.infAlterar"));
        bCancelar.setToolTipText(myResources.getString("cLogin.infCancelar"));
        tNome.setToolTipText(myResources.getString("cLogin.infNome"));
        tEmail.setToolTipText(myResources.getString("cLogin.infEmail"));
        tNick.setToolTipText(myResources.getString("cLogin.infNick"));
        tLogin.setToolTipText(myResources.getString("cLogin.infLogin"));
        tSenha.setToolTipText(myResources.getString("cLogin.infSenha"));
        tSenhaC.setToolTipText(myResources.getString("cLogin.infSenhaC"));
        login = LoginDAOS.consultLogin();
        inicialiaV(login);
        setVisible(true);
        setLocation(200,50);
        validacao v = new validacao();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        tEmail = new javax.swing.JTextField();
        lEmail = new javax.swing.JLabel();
        lSenha1 = new javax.swing.JLabel();
        lLogin = new javax.swing.JLabel();
        tSenha = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        tLogin = new javax.swing.JTextField();
        lNick = new javax.swing.JLabel();
        tNome = new javax.swing.JTextField();
        lNome = new javax.swing.JLabel();
        tSenhaC = new javax.swing.JPasswordField();
        lSenha = new javax.swing.JLabel();
        tNick = new javax.swing.JTextField();
        bCancelar = new javax.swing.JButton();
        bAlterar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setBackground(new java.awt.Color(255, 255, 255));

        tEmail.setBounds(150, 120, 210, 20);
        jLayeredPane1.add(tEmail, javax.swing.JLayeredPane.DEFAULT_LAYER);

        lEmail.setFont(new java.awt.Font("Showcard Gothic", 0, 12));
        lEmail.setText(myResources.getString("cLogin.email"));
        lEmail.setBounds(100, 130, 135, 15);
        jLayeredPane1.add(lEmail, javax.swing.JLayeredPane.DEFAULT_LAYER);

        lSenha1.setFont(new java.awt.Font("Showcard Gothic", 0, 12));
        lSenha1.setText(myResources.getString("cLogin.cSenha"));
        lSenha1.setBounds(70, 280, 135, 15);
        jLayeredPane1.add(lSenha1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        lLogin.setFont(new java.awt.Font("Showcard Gothic", 0, 12));
        lLogin.setText(myResources.getString("cLogin.login"));
        lLogin.setBounds(140, 220, 135, 15);
        jLayeredPane1.add(lLogin, javax.swing.JLayeredPane.DEFAULT_LAYER);
        tSenha.setBounds(190, 250, 168, 19);
        jLayeredPane1.add(tSenha, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel1.setFont(new java.awt.Font("A Damn Mess", 1, 36));
        jLabel1.setText(myResources.getString("titulo.alteraC"));
        jLabel1.setBounds(10, 20, 470, 41);
        jLayeredPane1.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        tLogin.setEnabled(false);
        tLogin.setBounds(190, 220, 168, 20);
        jLayeredPane1.add(tLogin, javax.swing.JLayeredPane.DEFAULT_LAYER);

        lNick.setFont(new java.awt.Font("Showcard Gothic", 0, 12));
        lNick.setText(myResources.getString("cLogin.nick"));
        lNick.setBounds(100, 160, 135, 15);
        jLayeredPane1.add(lNick, javax.swing.JLayeredPane.DEFAULT_LAYER);
        tNome.setBounds(150, 90, 212, 20);
        jLayeredPane1.add(tNome, javax.swing.JLayeredPane.DEFAULT_LAYER);

        lNome.setFont(new java.awt.Font("Showcard Gothic", 0, 12));
        lNome.setText(myResources.getString("cLogin.nome"));
        lNome.setBounds(90, 90, 50, 15);
        jLayeredPane1.add(lNome, javax.swing.JLayeredPane.DEFAULT_LAYER);
        tSenhaC.setBounds(190, 270, 168, 19);
        jLayeredPane1.add(tSenhaC, javax.swing.JLayeredPane.DEFAULT_LAYER);

        lSenha.setFont(new java.awt.Font("Showcard Gothic", 0, 12));
        lSenha.setText(myResources.getString("cLogin.senha"));
        lSenha.setBounds(130, 250, 135, 15);
        jLayeredPane1.add(lSenha, javax.swing.JLayeredPane.DEFAULT_LAYER);
        tNick.setBounds(200, 160, 160, 20);
        jLayeredPane1.add(tNick, javax.swing.JLayeredPane.DEFAULT_LAYER);

        bCancelar.setFont(new java.awt.Font("Showcard Gothic", 0, 12));
        bCancelar.setText(myResources.getString("cLogin.cancelar"));
        bCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCancelarActionPerformed(evt);
            }
        });
        bCancelar.setBounds(310, 320, 110, 23);
        jLayeredPane1.add(bCancelar, javax.swing.JLayeredPane.DEFAULT_LAYER);

        bAlterar.setFont(new java.awt.Font("Showcard Gothic", 0, 12));
        bAlterar.setText(myResources.getString("alteraC.alterar"));
        bAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAlterarActionPerformed(evt);
            }
        });
        bAlterar.setBounds(200, 320, 100, 23);
        jLayeredPane1.add(bAlterar, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel2.setBackground(new java.awt.Color(255, 255, 255));
        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/supertrunfo/stcI2.jpg"))); // NOI18N
        jLabel2.setBounds(0, 70, 450, 310);
        jLayeredPane1.add(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jLayeredPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 496, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jLayeredPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-512)/2, (screenSize.height-399)/2, 512, 399);
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Método invocado quando clica no botão Alterar.
     * @param evt
     */
    private void bAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAlterarActionPerformed
        if (validacao.validarNome(tNome.getText()) && validacao.validarEmail(tEmail.getText())
                && validacao.validarNick(tNick.getText())
                && validacao.validarSenha(tSenha.getText(), tSenhaC.getText())) {
            try {
                login = getDadosTela();
                if (LoginDAOS.alteraLogin(login) == 1) {
                        JOptionPane.showMessageDialog(null, "Conta alterada com sucesso");
                        log.fine("Alteração realizada com sucesso.");
                        setVisible(false);
                    } else {
                        JOptionPane.showMessageDialog(null, "Erro na alteração");
                        log.warning("Falha na alteração invalidos.");
                        inicialiaV(login);
                    }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Dados inválidos.");
                log.fine("Dados de alteração invalidos.");
                inicialiaV(login);
            }
        }
    }//GEN-LAST:event_bAlterarActionPerformed

    private void bCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelarActionPerformed
        if (JOptionPane.showConfirmDialog(null, "Tem certeza de que deseja cancelar?") == 0) {
            this.hide();// TODO add your handling code here:
            log.info("alteração de conta cancelado.");
        } else {
            return;
        }
}//GEN-LAST:event_bCancelarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bAlterar;
    private javax.swing.JButton bCancelar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JLabel lEmail;
    private javax.swing.JLabel lLogin;
    private javax.swing.JLabel lNick;
    private javax.swing.JLabel lNome;
    private javax.swing.JLabel lSenha;
    private javax.swing.JLabel lSenha1;
    private javax.swing.JTextField tEmail;
    private javax.swing.JTextField tLogin;
    private javax.swing.JTextField tNick;
    private javax.swing.JTextField tNome;
    private javax.swing.JPasswordField tSenha;
    private javax.swing.JPasswordField tSenhaC;
    // End of variables declaration//GEN-END:variables

    /**
     * Método que inicializa a janela com campos de preenchimento com informacões do Usuário (Login)
     * @param login
     */
    private void inicialiaV(Usuario login) {
        tNome.setText(login.getNome());
        tEmail.setText(login.getEmail());
        tNick.setText(login.getNick());
        tLogin.setText(login.getLogin());
        tSenha.setText(login.getSenha());
        tSenhaC.setText(login.getSenha());
    }

    /**
     * Método que recebe os (novos) dados dos campos de preenchimento do Usuário
     * @return
     */
    private Usuario getDadosTela() {
        Usuario login = new Usuario();
        login.setLogin(tLogin.getText());
        login.setSenha(tSenha.getText());
        login.setEmail(tEmail.getText());
        login.setNick(tNick.getText());
        login.setNome(tNome.getText());
        return login;
    }

    /**
     * Método que limpa os campos de preenchimento da janela Alterar
     */
    private void limpaTela() {

        tSenha.setText("");
        tLogin.setText("");
        tNome.setText("");
        tNick.setText("");
        tEmail.setText("");
        tSenhaC.setText("");

    }
}
